<template>
  <div ref="modal">
    <a-modal :getContainer="() => $refs.modal" v-model:visible="visible" width="800px" title="选择人员" @ok="handleOk" @cancel="cancel">
      <div class="select-personnel">
        <a-row>
          <a-col :span="8">
            <div class="menu_search">
              <a-input v-model:value="searchValue" placeholder="请输入" style="border-radius: 3px">
                <template #suffix>
                  <i class="iconfont icon-search"></i>
                </template>
              </a-input>
            </div>
            <a-tabs v-model:activeKey="activeKey">
              <a-tab-pane key="1" tab="人员列表"></a-tab-pane>
              <a-tab-pane key="2" tab="角色列表" v-if="isShowRole"></a-tab-pane>
            </a-tabs>
            <div v-if="activeKey == '1'">
              <a-tree
                :fieldNames="fieldNames"
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :tree-data="gData"
                @expand="onExpand"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                @check="onCheck"
                checkable
              >
                <template #title="{ name, isPerson, nickName }">
                  <div v-if="isPerson" class="text-ellipsis" :title="nickName">
                    <span v-if="nickName.indexOf(searchValue) > -1">
                      {{ nickName.substr(0, nickName.indexOf(searchValue)) }}
                      <span style="color: #f50">{{ searchValue }}</span>
                      {{ nickName.substr(nickName.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span v-else>{{ name }}</span>
                  </div>
                  <div v-else class="text-ellipsis" :title="name">
                    <span v-if="name.indexOf(searchValue) > -1">
                      {{ name.substr(0, name.indexOf(searchValue)) }}
                      <span style="color: #f50">{{ searchValue }}</span>
                      {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span v-else>{{ name }}</span>
                  </div>
                </template>
              </a-tree>
            </div>
            <div v-if="activeKey == '2'">
              <a-tree :fieldNames="fieldNames" :tree-data="gRoleData" @check="onCheckRole" checkable v-model:checkedKeys="roleCheckedKeys">
                <template #title="{ name }">
                  <span v-if="name.indexOf(searchValue) > -1">
                    {{ name.substr(0, name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ name }}</span>
                </template>
              </a-tree>
            </div>
          </a-col>
          <a-col :span="16">
            <div class="select-right">
              <a-checkbox :checked="true">全选 <span class="delete-text" @click="onRemoveAll">删除</span></a-checkbox>

              <div class="right-list">
                <ul v-if="currentCheckedrRole.length">
                  <li v-for="(item, index) in currentCheckedrRole" :key="index">
                    <a-checkbox :checked="true" @click="clickCheckBox(item, index, 'role')" class="a-checkbox"></a-checkbox>
                    <div class="img">
                      <img src="../../../../assets/img/icon_role.png" />
                    </div>
                    <div class="name">{{ item.name }}</div>
                  </li>
                </ul>
              </div>
              <div class="right-list">
                <ul>
                  <li v-for="(item, index) in currentCheckedrOrg" :key="index">
                    <a-checkbox :checked="true" @click="clickCheckBox(item, index, 'org')" class="a-checkbox"></a-checkbox>
                    <div class="img">
                      <img src="../../../../assets/img/icon_department.png" />
                    </div>
                    <div class="name">{{ item?.name }}</div>
                  </li>
                </ul>
              </div>
              <div class="right-list">
                <ul>
                  <li v-for="(item, index) in currentCheckedrPerson" :key="index">
                    <a-checkbox :checked="true" @click="clickCheckBox(item, index, 'person')" class="a-checkbox"></a-checkbox>
                    <div class="img">
                      <img src="../../../../assets/img/icon_headimg.png" />
                    </div>
                    <div class="name">{{ item?.nickName }}</div>
                  </li>
                </ul>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { reactive, computed, ref, getCurrentInstance, onMounted, watch, onUnmounted, createVNode, toRaw } from 'vue';
import type { TreeProps } from 'ant-design-vue';
const { proxy }: any = getCurrentInstance();
const props = defineProps({
  isShowRole: {
    type: Boolean,
    default: true
  }
});
const visible = ref<boolean>(true);
const activeKey = ref<string>('1');
const genData: TreeProps['treeData'] = [];
const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>('');
const autoExpandParent = ref<boolean>(true);
const dataList: TreeProps['treeData'] = [];
const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const roleCheckedKeys = ref<string[]>([]);
const currentCheckedNodes = ref<any>([]);
const currentCheckedrRole = ref<any>([]); //当前选择的角色
const currentCheckedrPerson = ref<any>([]); //当前选择的人员
const currentCheckedrOrg = ref<any>([]); //当前选择的机构部门
const fieldNames: any = {
  children: 'children',
  title: 'name',
  key: 'id',
  value: 'subTitle'
};
const gData = ref<TreeProps['treeData']>(genData); //机构+人员
const gRoleData = ref<TreeProps['treeData']>([]); //角色

const orgData = ref([]); //机构数据

const allChecked = ref<boolean>(true);

const emit = defineEmits(['save', 'cancel']);

const showModal = () => {
  visible.value = true;
};
const cancel = () => {
  visible.value = false;
  emit('cancel', false);
};
const handleOk = (e: MouseEvent) => {
  const data: any = [...currentCheckedrRole.value, ...currentCheckedrOrg.value, ...currentCheckedrPerson.value];
  const submitInfo = {
    roles: currentCheckedrRole.value.map((v: any) => v.id),
    depts: currentCheckedrOrg.value.map((v: any) => v.id),
    users: currentCheckedrPerson.value.map((v: any) => v.id)
  };
  emit('save', { data: data, info: submitInfo });
  visible.value = false;
};

const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

onMounted(() => {
  getOrgData();
  props.isShowRole && getRoleList();
});

//解绑
onUnmounted(() => {});

const setTreeData = (data: any) => {
  data = data.map((item: any) => {
    item.children = [];
    let subjectSimpleList = [];
    if (item?.code) {
      item.checkable = false;
    }
    if (item.subjectSimpleList) {
      item.subjectSimpleList.forEach((v: any) => {
        v.isPerson = true;
        v.name = v.nickName;
        subjectSimpleList.push(v);
      });
    }
    item.childOrg = item.childOrg || [];
    item.children = item.childOrg ? setTreeData(item.childOrg) : item.childOrg;
    item.children = item.childOrg.concat(subjectSimpleList);
    return {
      ...item
    };
  });
  return data;
};
const setPerson = (data) => {
  if (!data?.length) return;
  data?.map((item: any) => {
    item.isPerson = true;
    item.nickName = item.name;
  });
};
const originTreeData = ref([
  {
    children: [],
    name: '内部用户',
    id: 'internalData',
    key: 'internalData',
    checkable: false
  },
  {
    children: [
      {
        children: [],
        name: '客户',
        id: 'customer',
        key: 'customer',
        checkable: false
      },
      {
        children: [],
        name: '供应商',
        id: 'supplier',
        key: 'supplier',
        checkable: false
      },
      {
        children: [],
        name: '游客',
        id: 'subjectResSimple',
        key: 'subjectResSimple',
        checkable: false
      }
    ],
    name: '外部用户',
    id: 'externalData',
    key: 'externalData',
    checkable: false
  }
]);
//获取部门人员数据  customerResList 客户   orgResList 机构  subjectResSimpleList 游客  supplierResList 供应商
const getOrgData = async () => {
  proxy.$Http.api('system/subject/findSubjectTree', '', 'get').then((res) => {
    if (res && res.data) {
      let { supplierResList = [], orgResList = [], subjectResSimpleList = [], customerResList = [] } = res?.data;
      customerResList = customerResList?.filter?.((item) => item.name);
      setPerson(supplierResList);
      setPerson(subjectResSimpleList);
      setPerson(customerResList);
      originTreeData.value[0].children = setTreeData(orgResList);
      originTreeData.value[1].children[0].children = customerResList;
      originTreeData.value[1].children[1].children = supplierResList;
      originTreeData.value[1].children[2].children = subjectResSimpleList;

      gData.value = originTreeData.value;
      generateList(gData.value);
    }
  });
};
function generateList(data: TreeProps['treeData']) {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.id;
    const title = node.name;
    dataList.push({ key, title: title });
    if (node.children) {
      generateList(node.children);
    }
  }
}

function getParentKey(key: string | number, tree: TreeProps['treeData']): string | number | undefined {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
}

//获取角色列表
const getRoleList = async () => {
  proxy.$Http.api('system/role/list', {}, 'post').then((res) => {
    if (res && res.data) {
      gRoleData.value = res.data;
    }
  });
};

const onCheck = (checkedKeysList: any, checkedNodes: any) => {
  currentCheckedrPerson.value = checkedNodes.checkedNodes?.filter((item: any) => item.isPerson);
  currentCheckedrOrg.value = checkedNodes.checkedNodes?.filter((item: any) => !item.isPerson);
};
const onCheckRole = (checkedKeysList: any, checkedNodes: any) => {
  currentCheckedrRole.value = checkedNodes.checkedNodes;
};

watch(searchValue, (value) => {
  const expanded = dataList
    .map((item: TreeProps['treeData'][number]) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});
const handleGetDetail = (data, list, res) => {
  data.map((item) => {
    list?.map((val) => {
      if (item.id === val) {
        res.push(item);
      }
    });
    if (item?.children?.length > 0) {
      handleGetDetail(item.children, list, res);
    }
  });
};
const handleDetailShow = (data: any) => {
  data.depts?.map((item) => {
    checkedKeys.value?.push(item);
  });
  data.users?.map((item) => {
    checkedKeys.value.push(item);
  });
  data.roles?.map((item) => {
    roleCheckedKeys.value.push(item);
  });
  handleGetDetail(gData.value, data.depts, currentCheckedrOrg.value);
  handleGetDetail(gData.value, data.users, currentCheckedrPerson.value);
  handleGetDetail(gRoleData.value, data.roles, currentCheckedrRole.value);
};
// 移除处理
const clickCheckBox = (info, index, type) => {
  if (type === 'person') {
    currentCheckedrPerson.value.splice(index, 1);
    checkedKeys.value?.map?.((item, i) => {
      if (item === info.id) {
        checkedKeys.value.splice(i, 1);
      }
    });
  }
  if (type === 'org') {
    currentCheckedrOrg.value.splice(index, 1);
    checkedKeys.value?.map?.((item, i) => {
      if (item === info.id) {
        checkedKeys.value.splice(i, 1);
      }
    });
  }
  if (type === 'role') {
    currentCheckedrRole.value.splice(index, 1);
    roleCheckedKeys.value?.map?.((item, i) => {
      if (item === info.id) {
        roleCheckedKeys.value.splice(i, 1);
      }
    });
  }
};
// 全选移除
const onRemoveAll = () => {
  currentCheckedrPerson.value = [];
  currentCheckedrOrg.value = [];
  currentCheckedrRole.value = [];
  checkedKeys.value = [];
  roleCheckedKeys.value = [];
};
defineExpose({
  currentCheckedrRole,
  handleDetailShow
});
</script>

<style lang="less" scoped>
.select-personnel {
  height: 500px;
  overflow-y: auto;
  .select-right {
    padding: 0 20px;
    .delete-text {
      color: #005aea;
      margin-left: 24px;
    }
    .right-list {
      margin-bottom: 10px;
      overflow: auto;
      & > ul {
        display: flex;
        flex-wrap: wrap;
        li {
          // float: left;
          margin-top: 20px;
          margin-right: 10px;
          width: 80px;
          text-align: center;
          position: relative;
          .a-checkbox {
            position: absolute;
            right: 5px;
          }
          .img {
            margin-top: 5px;
            img {
              width: 40px;
              height: 40px;
            }
          }
          .name {
            margin-top: 3px;
          }
        }
      }
    }
  }
  .text-ellipsis {
    width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
:deep(.ant-modal-footer) {
  text-align: center;
}
</style>
